<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="onSubmit"
            @reset="reset"
        >
            <el-form :inline="true" :model="queryForm">
                <el-form-item :label="$t('dic.trainingLevel') + ':'">
                    <el-select v-model="queryForm.trainingLevel" clearable>
                        <el-option
                            v-for="item in options.trainingLevel"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
        </ConditionCard>
        <el-card v-loading="loading" shadow="never" body-style="padding: 24px;" class="card-margin">
            <h1 class="condition-title">{{ $t('culture.course.category') }}</h1>
            <div class="div-main clearfix">    
                <div class="float-left">
                    <el-input
                        v-model="queryForm.label"
                        :placeholder="$t('common.pla.pleaseInput') + $t('culture.course.category')"
                        clearable
                        style="width:250px"
                        @keyup.enter.native="filter"
                    >
                        <i
                            slot="suffix"
                            class="el-icon-search"
                            style="margin-top:10px;cursor:pointer"
                            @click="filter"
                        ></i>
                    </el-input>
                </div>
                <div class="float-right">
                    <el-button @click="showDeleteCoursesCategory">{{ $t('common.btn.delete') }}</el-button>
                    <el-button
                        type="primary"
                        @click="addCourseCategory()"
                    >{{ $t('common.btn.add') }}</el-button>
                </div>
            </div>
            <!--table -->
            <el-table
                :data="courses | sortByTime"
                stripe
                size="mini"
                @selection-change="chooseCourse"
            >
                <el-table-column type="selection" width="40"/>
                <el-table-column :label="$t('common.text.serialNum')" type="index" width="50"/>
                <el-table-column :label="$t('culture.course.categoryCn')" min-width="150">
                    <template slot-scope="props">
                        <el-tooltip :content="props.row.label" placement="bottom" effect="light">
                            <span>{{ props.row.label }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('culture.course.categoryEn')" min-width="150">
                    <template slot-scope="props">
                        <el-tooltip :content="props.row.labelEn" placement="bottom" effect="light">
                            <span>{{ props.row.labelEn }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('culture.course.parentCategory')" min-width="150">
                    <template slot-scope="props">
                        <el-tooltip :content="props.row.parentName" placement="bottom" effect="light">
                            <span>{{ props.row.parentName }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('culture.course.parentCategoryEn')" min-width="150">
                    <template slot-scope="props">
                        <el-tooltip :content="props.row.parentNameEn" placement="bottom" effect="light">
                            <span>{{ props.row.parentNameEn }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('dic.trainingLevel')" width="80">
                    <template slot-scope="props">{{ props.row.trainingLevel }}</template>
                </el-table-column>
                <!-- <el-table-column :label="$t('culture.course.creditLimit')" width="80">
                    <template slot-scope="props">
                        <el-tag
                            v-if="props.row.creditLimit === '1'"
                            type="success"
                        >{{ $t('common.text.yes') }}</el-tag>
                        <el-tag
                            v-if="props.row.creditLimit === '0'"
                            type="danger"
                        >{{ $t('common.text.no') }}</el-tag>
                    </template>
                </el-table-column> -->
                <el-table-column :label="$t('culture.course.publicElective')" width="80">
                    <template slot-scope="props">
                        <el-tag
                            v-if="props.row.isElective == 1"
                            :type="success"
                        >{{ $t('common.text.yes') }}</el-tag>
                        <el-tag
                            v-if="props.row.isElective == 0 "
                            type="danger"
                        >{{ $t('common.text.no') }}</el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="备注">
          <template slot-scope="props">
            <el-tooltip :content="props.row.remark" placement="bottom" effect="light">
                <span>{{ props.row.remark }}</span>
            </el-tooltip>
          </template>
                </el-table-column>-->
                <el-table-column :label="$t('common.text.operation')" width="120">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="mini"
                            @click="editCourseCategory(scope.row)"
                        >{{ $t('common.btn.edit') }}</el-button>
                        <el-button
                            type="text"
                            size="mini"
                            @click="showDeleteCourseCategory(scope.row)"
                        >{{ $t('common.btn.delete') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col>
                    <el-pagination
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryForm.pageSize_"
                        :total="queryForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float:right;margin-top:10px"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </el-col>
            </el-row>
        </el-card>
        <el-dialog
            :title="dialogTitle"
            :visible.sync="showCourseDialog"
            width="40%"
            @close="resetFormValidate()"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form
                ref="courseForm"
                :model="courseForm"
                :rules="courseRules"
                label-width="150px"
                label-position="right"
                style="margin-left:12px;"
            >
                <el-row :gutter="20">
                    <el-col :span="18">
                        <el-form-item
                            :label="$t('dic.trainingLevel') + '：'"
                            prop="trainingLevel"
                        >
                            <el-select
                                v-model="courseForm.trainingLevel"
                                :disabled="isEdit"
                                style="width:100%"
                                @change="selectTrainLevelChange"
                            >
                                <el-option
                                    v-for="item in dialogOptions.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item
                            :label="$t('culture.course.creditLimit') + '：'"
                            prop="creditLimit"
                        >
                            <el-radio-group v-model="courseForm.creditLimit">
                                <el-radio label="1">{{ $t('common.text.yes') }}</el-radio>
                                <el-radio label="0">{{ $t('common.text.no') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="18">
                        <el-form-item
                            :label="$t('culture.course.categoryCn') + '：'"
                            prop="courseChName"
                        >
                            <el-input
                                v-model="courseForm.courseChName"
                                type="text"
                                placeholder
                                style="width:100%"
                                maxlength="32"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="18">
                        <el-form-item
                            :label="$t('culture.course.categoryEn') + '：'"
                            prop="courseEnName"
                        >
                            <el-input
                                v-model="courseForm.courseEnName"
                                type="text"
                                placeholder
                                style="width:100%"
                                maxlength="64"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="18">
                        <el-form-item :label="$t('culture.course.parentCategory') + '：'">
                            <el-select
                                v-model="courseForm.parentId"
                                :disabled="isEdit"
                                style="width:100%"
                                @change="selectCourseParentId"
                            >
                                <el-option
                                    v-for="item in dialogOptions.courses"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    :style="{textIndent:item.indent+'px'}"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18">
                        <el-form-item
                            v-show="isElectiveShow === 0"
                            :label="$t('culture.course.publicElective') + '：'"
                            prop="isElective"
                        >
                            <el-radio-group
                                v-model="courseForm.isElective"
                                :disabled="!!(courseForm.parentId)"
                            >
                                <el-radio label="1">{{ $t('common.text.yes') }}</el-radio>
                                <el-radio label="0">{{ $t('common.text.no') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input v-model="courseForm.remark" :rows="4" type="textarea" style="width:100%" maxlength="255"/>
            </el-form-item>
          </el-col>
                </el-row>-->
            </el-form>
            <el-row :gutter="0">
                <el-col :span="24">
                    <div class="float-right">
                        <el-button @click="cancelDialog">{{ $t('common.btn.cancel') }}</el-button>
                        <el-button
                            type="primary"
                            @click="confirmDialog"
                        >{{ $t('common.btn.confirm') }}</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>
<script>
import bus from "common/src/utils/bus";
import { queryDic, findTrainingLevelByProjId } from "common/src/api/dictionary";
import {
    getCourseCategoryList,
    getCourseAllList,
    addCourseLabel,
    deleteCourseById,
    courseInfoById,
    updateCourse
} from "common/src/api/courseTemplate";
const DELETE_TYPE = {
    SINGLE: "SINGLE",
    BATCH: "BATCH"
};
const ELECTIVE_TYPE = {
    // 对话框公共选修的状态类型，-1：不可见，0：select类型，1：文本(课程分类为根节点时，显示select类型，子节点时，显示文本不可修改)
    NO_VISIBLE: -1,
    SELECT: 0,
    TEXT: 1
};
export default {
    name: "course-category-manage",
    data() {
        return {
            loading: false,
            showCourseDialog: false,
            dialogTitle: "",
            isElectiveShow: ELECTIVE_TYPE.SELECT,
            isEdit: false,
            queryForm: {
                trainingLevel: "",
                label: "", // 课程名称
                pageNum_: 1,
                pageSize_: 20,
                total: 0
            },
            courseForm: {
                courseId: "",
                trainingLevel: "",
                parentId: 0,
                courseChName: "",
                courseEnName: "",
                // remark: '',
                isElective: "0",
                //creditLimit: "0"
            },
            options: {
                trainingLevel: []
            },
            dialogOptions: {
                trainingLevel: [],
                courses: [],
                isElective: []
            },
            courses: [],
            chooseCourses: [],
            deleteType: "", // 删除类型：单个删除或批量删除
            deleteId: "", // 单个删除项Id
            courseRules: {
                courseChName: [
                    {
                        required: true,
                        message: "请输入课程类别(中文)",
                        trigger: "blur"
                    },
                    {
                        min: 1,
                        max: 32,
                        message: "长度在 1 到 32 个字符",
                        trigger: "blur"
                    }
                ],
                courseEnName: [
                    {
                        required: true,
                        message: "请输入课程类别(英文)",
                        trigger: "blur"
                    },
                    {
                        min: 1,
                        max: 64,
                        message: "长度在 1 到 64 个字符",
                        trigger: "blur"
                    }
                ],
                trainingLevel: [
                    {
                        required: true,
                        message: "请选择培养层次",
                        trigger: "blur"
                    }
                ],
                creditLimit: [
                    {
                        required: true,
                        message: "请选择学分限制",
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    mounted: function() {
        bus.$on("updateCurrentManageDeptId", currentManageDeptId => {
            this.queryForm.projId = currentManageDeptId;
            this.initTrainingLevelOptions();
        });
        this.init();
        this.initProjId();
        this.initTrainingLevelOptions();
    },
    methods: {
        initProjId() {
            let currentUser =
                (this.$store.state.session && this.$store.state.session.user) ||
                JSON.parse(localStorage.getItem("user"));
            this.queryForm.projId = currentUser.currentManageDptId;
        },
        initTrainingLevelOptions() {
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    this.queryForm.trainingLevel = "";
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.options[optionKey] = [];
            _.each(dataObj, level => {
                this.options[optionKey].push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        init() {
            // this.queryForm['x-token'] =
            //           this.$store.state.session.sessionid ||
            //           localStorage.getItem('sessionid') ||
            //           ''
            // // 绑定年级
            // const now = new Date()
            // let currentYear = now.getFullYear(),
            //   minYear = currentYear - 5
            // for (let year = currentYear; year > minYear; year--) {
            //   const obj = { label: year, value: year }
            //   this.options.grade.push(obj)
            //   this.dialogOptions.grade.push(obj)
            // }
            // 绑定公共选修
            this.dialogOptions.isElective.push(
                { label: "是", value: 1 },
                { label: "否", value: 0 }
            );

            // 绑定培养层次
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_PYCC"]
            };
            queryDic(data)
                .then(res => {
                    if (res.code === 200) {
                        // 追加下拉框“全部”选项
                        this.options["trainingLevel"].push({
                            value: "",
                            label: this.$t("common.text.all")
                        });
                        for (const key in res.data.X_PYCC) {
                            //	if (key != 4 && key != 6) {
                            this.options["trainingLevel"].push({
                                value: key,
                                label: res.data.X_PYCC[key]
                            });
                            this.dialogOptions["trainingLevel"].push({
                                value: key,
                                label: res.data.X_PYCC[key]
                            });
                            //	}
                        }
                    }
                })
                .catch(err => {
                    console.log(err);
                });
            this.onSubmit(); // 进入页面，默认筛选
        },
        reset() {
            this.queryForm.trainingLevel = "";
            this.queryForm.label = "";
            this.getCourseList();
        },
        onSubmit() {
            this.getCourseList();
        },
        getCourseList(pageNumReset = true) {
            if (pageNumReset) {
                this.queryForm.pageNum_ = 1;
            }
            getCourseCategoryList(this.queryForm).then(response => {
                if (response.code === 200) {
                    this.queryForm.total = response.data.total_;
                    if(response.data.list && response.data.list.length > 0){
                         response.data.list.forEach(c => {
                            const trainingLevel = this.options.trainingLevel.find(
                                option => option.value === c.trainingLevel
                            );
                            if (trainingLevel) {
                                c.trainingLevel = trainingLevel.label;
                            }
                        });
                        this.courses = response.data.list.sort(
                            (item1, item2) => item2.createTime - item1.createTime
                        );
                    } else{
                        this.courses = []
                    }
                }
            });
        },
        filter() {
            this.onSubmit();
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getCourseList();
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val;
            this.getCourseList(false);
        },
        // 选择复选框
        chooseCourse(val) {
            this.chooseCourses = val;
        },
        // 重置课程对话框
        resetCourseDialog() {
            this.courseForm.courseId = "";
            this.courseForm.trainingLevel = "";
            this.courseForm.parentId = "";
            this.courseForm.courseChName = "";
            this.courseForm.courseEnName = "";
            this.courseForm.remark = "";
            this.courseForm.isElective = "0";
            this.dialogOptions.courses.length = 0;
            this.showCourseDialog = true;
        },
        // 课程分类过滤
        courseFilter(data, trainingLevel = "", filterId = -1) {
            if (trainingLevel !== "") {
                data = data.filter(row => row.trainingLevel === trainingLevel);
            }
            const array = [];
            //array.push({ label: "", value: "", indent: 0, level: 0 });
            if (data.length > 0) {
                this.loadCategoryRelation(array, data, 0, filterId);
            }
            this.dialogOptions.courses = array;
        },
        // 创建课程类别
        addCourseCategory(trainingLevel = "") {
            this.dialogTitle = this.$t("culture.course.create");
            this.isEdit = false;
          //  this.isElectiveShow =
               // trainingLevel === "1"
                  //  ? ELECTIVE_TYPE.SELECT
                   // : ELECTIVE_TYPE.NO_VISIBLE;
            if (trainingLevel === "") {
                this.resetCourseDialog();
            }
            if(trainingLevel!==""){
                 this.getAllCourse(response => {
               this.courseFilter(response.data, trainingLevel);
            });
            }
           

        },
        // 编辑课程类别
        editCourseCategory(row) {
            this.dialogTitle = this.$t("culture.course.edit");
            this.isEdit = true;
            this.resetCourseDialog();
            courseInfoById(row.id) // 查询当前课程分类详情
                .then(response => {
                    if (response.code === 200 && response.data) {
                        this.courseForm.parentId =
                            response.data.parentId === 0
                                ? ""
                                : response.data.parentId;
                        this.courseForm.courseId = row.id;
                        this.courseForm.trainingLevel =
                            response.data.trainingLevel;
                        this.courseForm.courseChName = response.data.label;
                        this.courseForm.courseEnName = response.data.labelEn;
                        this.courseForm.remark = response.data.remark;
                        this.courseForm.isElective =
                            response.data.isElective + "";
                        // this.courseForm.creditLimit =
                        //     response.data.creditLimit + "";
                        this.isElectiveShow = ELECTIVE_TYPE.SELECT;
                            
                        this.getAllCourse(response => {
                            this.courseFilter(
                                response.data,
                                this.courseForm.trainingLevel,
                                row.id
                            );
                        });
                    }
                });
        },
        // 获取所有课程分类
        getAllCourse(callbackFn) {
            getCourseAllList().then(response => {
                if (response.code === 200) {
                    callbackFn(response);
                }
            });
        },
        // 显示课程分类父子关系
        loadCategoryRelation(
            array = [],
            dataSource,
            parentId = 0,
            filterId = -1, // 过滤Id
            indent = 0, // 缩进距离
            level = 1 // 层级
        ) {
            dataSource.forEach(p => {
                if (p.parentId === parentId && p.id !== filterId) {
                    array.push({
                        label: p.label,
                        value: p.id,
                        indent: indent,
                        level: level,
                        trainingLevel: p.trainingLevel,
                        isElective: p.isElective
                    });
                    this.loadCategoryRelation(
                        array,
                        dataSource,
                        p.id,
                        filterId,
                        indent + 20,
                        level + 1
                    );
                }
            });
        },
        // 显示批量删除对话框
        showDeleteCoursesCategory() {
            if (this.chooseCourses.length === 0) {
                this.$message({
                    type: "info",
                    message: this.$t("common.pla.plsSelectRecord")
                });
                return;
            }
            this.$confirm(
                this.$t("common.tips.beSure"),
                this.$t("common.text.info"),
                {
                    confirmButtonText: this.$t("common.btn.confirm"),
                    cancelButtonText: this.$t("common.btn.cancel"),
                    type: "warning"
                }
            ).then(() => {
                this.deleteType = DELETE_TYPE.BATCH;
                this.deleteId = "";
                this.confirmDelete();
            });
        },
        // 显示单个删除对话框
        showDeleteCourseCategory(row) {
            const _this = this;
            _this
                .$confirm(
                    _this.$t("common.tips.beSure"),
                    _this.$t("common.text.info"),
                    {
                        confirmButtonText: _this.$t("common.btn.confirm"),
                        cancelButtonText: _this.$t("common.btn.cancel"),
                        type: "warning"
                    }
                )
                .then(() => {
                    if (!(row.isLeafNode && row.isLeafNode * 1)) {
                        this.deleteType = DELETE_TYPE.SINGLE;
                        this.deleteId = row.id;
                        this.confirmDelete();
                    } else {
                        this.$confirm(
                            "确认删除此课程下绑定的子课程吗？",
                            "提示",
                            {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning"
                            }
                        )
                            .then(() => {
                                this.deleteType = DELETE_TYPE.SINGLE;
                                this.deleteId = row.id;
                                this.confirmDelete();
                            })
                            .catch(err => {
                                console.log(err);
                            });
                    }
                })
                .catch(e => {});
        },
        // 取消对话框课程分类
        cancelDialog() {
            this.showCourseDialog = false;
        },
        resetFormValidate() {
            // 清除表单校验
            this.$refs.courseForm.resetFields();
        },
        // 保存对话框课程分类
        confirmDialog() {
            this.$refs.courseForm.validate(valid => {
                if (!valid) {
                    return;
                }
                const data = {
                    trainingLevel: this.courseForm.trainingLevel,
                    label: this.courseForm.courseChName,
                    labelEn: this.courseForm.courseEnName,
                    parentId: this.courseForm.parentId || 0,
                    remark: this.courseForm.remark,
                    level: 1,
                    isElective: this.courseForm.isElective,
                    //creditLimit: this.courseForm.creditLimit
                };
                if (this.courseForm.parentId) {
                    const parent = this.dialogOptions.courses.find(
                        c => c.value === this.courseForm.parentId
                    );
                    if (parent) {
                        data.level = parent.level + 1;
                    }
                }
                // 根据courseId判断是创建或更新
                if (this.courseForm.courseId) {
                    data["id"] = this.courseForm.courseId;
                    updateCourse(data).then(response => {
                        if (response.code === 200) {
                            this.$message({
                                type: "success",
                                message: "保存成功"
                            });
                            this.showCourseDialog = false;
                            this.getCourseList();
                        }
                    });
                } else {
                    addCourseLabel(data).then(response => {
                        if (response.code === 200) {
                            this.$message({
                                type: "success",
                                message: "创建成功"
                            });
                            this.showCourseDialog = false;
                            this.getCourseList();
                        }
                    });
                }
            });
        },

        // 确定删除
        confirmDelete() {
            let ids = [];
            if (this.deleteType === DELETE_TYPE.SINGLE) {
                ids = [this.deleteId];
            } else {
                ids = this.chooseCourses.map(c => c.id);
            }
            if (ids.length > 0) {
                deleteCourseById(ids).then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                        this.getCourseList();
                    }
                });
            }
        },
        selectTrainLevelChange(value) {
            this.dialogOptions.courses.length = 0;
            this.addCourseCategory(value);
            this.courseForm.parentId = "";
        },
        selectCourseParentId(value) {
            // 选择了父课程类别名时需要判断公共选修
            this.isElectiveShow = ELECTIVE_TYPE.SELECT;
            if (value !== "") {
                for (let i = 0; i < this.dialogOptions.courses.length; i++) {
                    const course = this.dialogOptions.courses[i];
                    if (course.value === value) {
                        this.isElectiveShow = ELECTIVE_TYPE.SELECT;
                        this.courseForm.isElective = course.isElective;
                        break;
                    }
                }
            }
        },
        getisElectiveText() {
            const option = this.dialogOptions.isElective.find(
                option => option.value === this.courseForm.isElective
            );
            return option ? option.label : "";
        }
    }
};
</script>
<style scoped>
    .div-main {
    margin-bottom: 16px;
  }
</style>
